package com.customization.api.e9sso.cmd;

import com.alibaba.fastjson.JSONObject;

import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;

import com.engine.workflow.biz.publicApi.RequestOperateBiz;

import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


public class SubmitCmd4Kb202008 extends AbstractCommonCommand<Map<String,Object>> {

    private HttpServletRequest request=null;
    public SubmitCmd4Kb202008(User user, HttpServletRequest request) {
        this.user = user;
        this.params = ParamUtil.request2Map(request);
        this.request=request;

        Enumeration<String> er = request.getParameterNames();
        while (er.hasMoreElements()) {
            String name = (String) er.nextElement();
            String value = request.getParameter(name);
            this.params.put(name, value);
        }
        Console.log(this.params.toString());

        params=this.getHeadersInfo(request,params);
    }
    private Map<String, Object> getHeadersInfo(HttpServletRequest request,Map<String, Object> map) {

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String uuid=UUID.randomUUID().toString();
        Console.log(uuid+"输入参数params:"+params.toString());
        Map<String, Object> apidatas = new HashMap<String, Object>();
        apidatas.put("status",true);
        apidatas.put("msg","提交成功!");

        RecordSet rs=new RecordSet();

        String approverWorkcode=Util.null2String(params.get("approverWorkcode"));
        String requestId=Util.null2String(params.get("requestId"));



        RecordSet rst= new RecordSet();
        String  sql=" update  uf_DispatchSSF set  approver_workcode='"+approverWorkcode+"' where request_id='"+requestId+"'";
        Console.log("sql:"+sql);
        rst.execute(sql);

        WorkflowRequestOperatePA workflowRequestOperatePA = new WorkflowRequestOperatePAImpl();;
        //2021/3/10 12:21 lth    增加签字意见里面显示支付出纳名称;
        ReqOperateRequestEntity request2Entity=RequestOperateBiz.request2Entity(this.request);

        /*
        if(!approverWorkcode.equals("")) {
            request2Entity.setRemark(request2Entity.getRemark() + "</br></br>流程已经到达支付环节，如有疑问请联系 <a href='/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/3627' target='_blank'>邹华俊</a>");
        }
        */
        //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  Start
        String sqls=" select  CURRENTNODEID,WORKFLOWID from  workflow_requestbase where requestid='"+requestId+"'";
        rst.execute(sqls);
        String currentNodeId="";
        String workflowId="";
        Console.log("查询当前节点:"+sqls);
        if(rst.next()){
            currentNodeId=rst.getString("CURRENTNODEID");
            workflowId=rst.getString("WORKFLOWID");
        }
        //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  end


        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(2, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .build();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "requestId="+requestId+"&remark="+Util.null2String(params.get("remark")));
        Request request = new Request.Builder()
                .url("http://127.0.0.1/api/workflow/paService/submitRequest")
                .method("POST", body)
                .addHeader("appid", Util.null2String(params.get("appid")))
                .addHeader("token", Util.null2String(params.get("token")))
                .addHeader("userid", Util.null2String(params.get("userid")))
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Console.log("开始执行");
            Response response = client.newCall(request).execute();
            Console.log("执行结果："+response.isSuccessful());
            String respStr = response.body().string();
            JSONObject result = JSONObject.parseObject(respStr);

            Console.log("submitRequest-result:"+result.toString());

            String code= Util.null2String(result.get("code"));
            if(!code.equals("SUCCESS")){
                apidatas.put("status",false);
                apidatas.put("msg","提交失败!");
                apidatas.put("errMsg",""+result.toString());
                apidatas.put("code",code);
                Console.log(uuid+"返回值:"+apidatas.toString());
                return apidatas;
            }else{


                //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  Start
                String nextPayNode=","+Util.null2String(rst.getPropValue("angel_fna", "nextPayNode_NodeIds"))+",";
                 //  Console.log("nextPayNode:"+nextPayNode);
                 // Console.log("currentNodeId:"+currentNodeId);
                //Console.log("&nextPayNode.contains(\",\"+currentNodeId+\",\"):"+(nextPayNode.contains(","+currentNodeId+",")));
                if(!currentNodeId.equals("")&&!nextPayNode.equals(",,")&&nextPayNode.contains(","+currentNodeId+",")){
                    sqls=" select  logid,REMARK,nodeid,logtype from  WORKFLOW_REQUESTLOG  where   (logtype='0'  or logtype='2')   and nodeid='"+currentNodeId+"' and  requestid='"+requestId+"'";
                    Console.log("查询当前节点的签字意见:"+sqls);
                    rst.execute(sqls);
                    String logid="";
                    if(rst.next()){
                        logid=rst.getString("logid");
                    }
                    if(!"".equals(logid)) {



                        sqls="select formid from  workflow_base where id='"+workflowId+"'";
                        Console.log("formid:"+sqls);
                        rst.execute(sqls);
                        rst.first();
                        int formid=rst.getInt("formid");


                        sqls="select * from  formtable_main_"+Math.abs(formid)+" where requestid='"+requestId+"'";
                        Console.log("gsdm:"+sqls);
                        rst.execute(sqls);
                        rst.first();


                        String gsdm=Util.null2String(rst.getString("gsdm5"));
                        if(gsdm.equals("")){
                            gsdm=Util.null2String(rst.getString("gsdm2"));
                        }else{
                            gsdm=Util.null2String(rst.getString("gsdm"));
                        }

                        sqls=" select gsdm,cn from uf_companyTreasurer where gsdm='"+gsdm+"'";
                        Console.log("resourceid:"+sqls);
                        rst.execute(sqls);
                        boolean isUpdate=false;
                        String cn="3627";
                        String lastname="邹华俊";
                        if(rst.next()){
                            cn=rst.getString("cn");
                            try {
                                ResourceComInfo rci=new ResourceComInfo();
                                lastname=rci.getLastname(cn);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            isUpdate=true;
                        }

                        sqls = " update  WORKFLOW_REQUESTLOG  set REMARK=REMARK||'</br></br>流程已经到达支付环节，如有疑问请联系 <a href=''/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/"+cn+"'' target=''_blank''>"+lastname+"</a>。</br></br>' where logid='"+logid+"'   and nodeid='" + currentNodeId + "' and  requestid='" + requestId + "'";
                        Console.log("updateSql:"+sqls);
                        if(isUpdate) {
                            rst.execute(sqls);
                        }

                        Console.log(isUpdate+"更新当前签字意见:" + sqls);

                    }
                }else{
                    Console.log("不在支付节点审核环节");

                }
                //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  End

            }
        } catch (IOException e) {
            e.printStackTrace();
            e.printStackTrace();
            apidatas.put("status",false);
            apidatas.put("errMsg",e.toString());
            apidatas.put("msg","提交失败");
            return apidatas;
        }

        Console.log(uuid+"返回值:"+apidatas.toString());
        return apidatas;
    }



}
